package com.xinbochuang.machine.admin.controller.macroom;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.cell.CellUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.dto.MacRoomDto;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.xinbochuang.machine.admin.domain.macRoom.EquCabinet;
import com.xinbochuang.machine.admin.domain.macRoom.Equipment;
import com.xinbochuang.machine.admin.domain.macRoom.MacRoom;
import com.xinbochuang.machine.admin.domain.macRoom.Ulocation;
import com.xinbochuang.machine.admin.service.macRoom.IMacRoomService;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import sun.security.provider.MD4;

/**
 *
 * @author 杜文博
 * @date 2020-09-08
 */
@RestController
@RequestMapping("/mac-room")
public class MacRoomController extends BaseController {

	@Autowired
	private IMacRoomService macRoomService;


	/**
	 * 根据机房名称查询机房信息
	 * @param macRoom
	 * @return
	 */
	@GetMapping("/list")
	public TableDataInfo getEquDetailList(MacRoom macRoom){
		return  getDataTable(macRoomService.findMacRoomByNameForPage(macRoom));
	}

	/**
	 * 获取所有机房信息
	 */
	@GetMapping("/allList")
	public AjaxResult getEquAllList(MacRoom macRoom){
		return AjaxResult.data(macRoomService.equAllList(macRoom));
	}

	/**
	 * 添加机房负责人
	 * @param macRoom
	 * @return
	 */
	@PutMapping("/addMacPrincipal")
	public AjaxResult addMacPrincipal(@RequestBody MacRoom macRoom){
		Integer result = null ;
		result = macRoomService.addMacPrincipal(macRoom);
		if(result==1){
			return AjaxResult.ok();
		}else {
			return AjaxResult.error();
		}
	}

	/**
	 * 批量添加机房安全员
	 * @param macRoomDto
	 * @return
	 */
	@PutMapping("/addMacGuards")
	public AjaxResult addMacGuardS(@RequestBody MacRoomDto macRoomDto){
		Integer result = null;
		result = macRoomService.addMacGuard(macRoomDto);
		if(result==1){
			return AjaxResult.ok();
		}else {
			return AjaxResult.error();
		}
	}

	/**
	 * 根据机房Id查询机房详情
	 */
	@GetMapping("/macDetail")
	public AjaxResult getMacDetail(@RequestParam("uuid") String uuid){
		return AjaxResult.data(macRoomService.getMacDetail(uuid));
	}

	//查询安全员
	@GetMapping("/getMacguard")
		public AjaxResult getMacguard (){
			return AjaxResult.data(macRoomService.getMacGuard());
	}

	/**
	 * 通过机房Id查询机柜列表
	 * @param response
	 * @param macId
	 * @return
	 */
	@GetMapping("/cabinet/list")
	public AjaxResult getCabinetList(HttpServletResponse response, @RequestParam(value = "macId")
		String macId){
		List<EquCabinet> list = macRoomService.finEquCabinetListByMacId(macId);
		return AjaxResult.data(list);
	}

	/**
	 * 删除机房
	 * @param response
	 * @param macRoom
	 * @return
	 */
	@PutMapping("/update")
	public AjaxResult deleteMacRoomById(HttpServletResponse response, @RequestBody MacRoom macRoom){
		return toAjax(macRoomService.updateByMacId(macRoom.getUuid()));
	}

	/**
	 * 机房导入
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/back/upgrade/fileupload")
	public AjaxResult fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
		// 项目在容器中实际发布运行的根路径
		String realPath = request.getSession().getServletContext().getRealPath("/");
		// 自定义的文件名称
		String trueFileName = String.valueOf(System.currentTimeMillis()) + new Random().nextInt();
		String path = realPath + trueFileName;
		File file1 = new File(path);
		file.transferTo(file1);
		ExcelReader reader = ExcelUtil.getReader(file1);
		Workbook workbook = reader.getWorkbook();
		//获取sheet
		Sheet sheetAt = workbook.getSheetAt(0);
		String macRommName = workbook.getSheetAt(0).getSheetName();
		List<MacRoom> macRoomlist = macRoomService.findMacRoomByName(macRommName);
		if(macRoomlist.size()>0){
			macRoomService.delteMacroomById(macRoomlist.get(0).getUuid());
		}
		String macUUID =  UUID.randomUUID().toString().trim().replaceAll("-", "");
		String equipmentUUID = "";
		String cabinetUUID = "";
		String ulocationUUID = "";
		MacRoom macRoom = new MacRoom();
		EquCabinet equCabinet = new EquCabinet();
		Ulocation ulocation = new Ulocation();
		Equipment equipment = new Equipment();
		macRoom.setUuid(macUUID);
		macRoom.setMacName(macRommName.replaceAll(" ",""));
		macRoom.setDelteFlag(0);
		macRoom.setCreateTime(DateUtil.now());
		macRoom.setUpdateTime(DateUtil.now());
		//将机房信息插入机房表
		macRoomService.insertMacroom(macRoom);
		//获取定位用的行列点
		String key="设备高度";
		int rowNumRange=50;
		int columnRange=1;
		//获取定位元素的合集
		List<CellAddress> arrs = getLocationCellAddress(sheetAt, key);
		List<List<String>> result=new ArrayList<>();
		//通过定位元素和行列范围获取想要的结果
		arrs.forEach(arr-> result.add(getFilterResult(sheetAt,arr,rowNumRange,columnRange)));
		//返回结果集
		List<List<String>> result2=result;
		Integer endResult = null;
		if(result2.size()!=0){
			//遍历机房内机柜数据
			for(int i=0;i<result2.size();i++){
				String [] cabinetStr = result2.get(i).get(0).split(":",2);
				if(cabinetStr.length==2) {
						equCabinet.setCabinetName(cabinetStr[0].replaceAll(" ",""));
						equCabinet.setUlocationQuantity(cabinetStr[1].replaceAll(" ",""));
						ulocation.setUfloorNum(cabinetStr[1].replaceAll(" ",""));
				}
					equCabinet.setEnergyName(result2.get(i).get(1).replaceAll(" ",""));
					cabinetUUID = UUID.randomUUID().toString().trim().replaceAll("-", "");
					equCabinet.setUuid(cabinetUUID);
					equCabinet.setMacId(macUUID);
					equCabinet.setDeleteFlag(0);
					equCabinet.setCreateTime(DateUtil.now());
					equCabinet.setUpdateTime(DateUtil.now());

					ulocationUUID = UUID.randomUUID().toString().trim().replaceAll("-", "");
					ulocation.setUuid(ulocationUUID);
					ulocation.setCabinetId(cabinetUUID);
					ulocation.setCreateTime(DateUtil.now());
					ulocation.setUpdateTime(DateUtil.now());
					ulocation.setDelteFlag(0);
					macRoomService.insertUlocation(ulocation);

				//获取设备数组
				List<String> equlist = result2.get(i);
				//设备数组去空处理
				List<String> equlistResult=equlist.stream().filter(string -> !string.isEmpty()).collect(Collectors
					.toList());
				//数组去重
				Set set = new HashSet();
				List newList = new ArrayList();
				for (Iterator iter = equlistResult.iterator(); iter.hasNext();) {
					Object element = iter.next();
					if (set.add(element)){
						newList.add(element);
					}
				}
				equlistResult.clear();
				equlistResult.addAll(newList);
				//遍历机柜内设备数据
				for(int j =0;j<equlistResult.size();j++){
					String [] str = equlistResult.get(j).split(":",3);
					if(str.length ==3){
						equipment.setEquName(str[0]);
						equipment.setEquHeight(str[1]);
						equipment.setEquState(str[2]);
						equipmentUUID = UUID.randomUUID().toString().trim().replaceAll("-", "");
						equipment.setUuid(equipmentUUID);
						equipment.setCabinetId(cabinetUUID);
						equipment.setUlocationId(ulocationUUID);
						equipment.setCreateTime(DateUtil.now());
						equipment.setUpdateTime(DateUtil.now());
						equipment.setDeleteFlag(0);
						//插入设备数据
						macRoomService.inserEquipment(equipment);
					}

				}
				//插入机柜数据
				 endResult =  macRoomService.insertEquCabinet(equCabinet);
			}
		}
		if(endResult==1){
			return  toAjax(true);
		}else{
			return toAjax(false);
		}
	}

	/**
	 * 通过单元格中的内容获取定位点的坐标
	 * @param sheet  Excel worksheet
	 * @param key  定位内容
	 * @return List<CellAddress> 定位坐标集合
	 */
	private List<CellAddress> getLocationCellAddress(Sheet sheet,String key){
		List<CellAddress> arrs = new ArrayList<>();
		sheet.forEach(row-> row.forEach(cell -> {
			//判断单元格格式是否是字符串
			if (cell.getCellType() == CellType.STRING) {
				//获取内容为设备高度的单元格位置
				if (cell.getStringCellValue().equals(key)) {
					arrs.add(cell.getAddress());
				}
			}
		}));
		return arrs;
	}
	/**
	 * 获取筛选结果
	 * @param cellAddress  定位元素地址
	 * @param rowNumRange  行的范围大小   50
	 * @param columnRange  列的范围大小  1
	 * @param sheet   Excel worksheet
	 * @return List<String>  查找单元的结果集
	 */
	private List<String> getFilterResult(Sheet sheet,CellAddress cellAddress,int rowNumRange,int columnRange){
		//符合要求的结果list
		List<String> temp = new ArrayList<>();
		//定位元素所在行
		int locationRow = cellAddress.getRow();
		//定位元素所在列
		int locationColumn =cellAddress.getColumn();
		for (int i=0;i<rowNumRange;i++){
			Cell targetCellValue = getTargetCellValue(locationRow + i, locationColumn + columnRange, sheet);
			String s = CellUtil.getCellValue(targetCellValue).toString();
			CellStyle cellStyle = targetCellValue.getCellStyle();
			//获取填充色
			short fillForegroundColor = cellStyle.getFillForegroundColor();
			temp.add(s);
		}
		return temp;
	}
	/**
	 * 通过行列获取Cell
	 * @param rowNum  行
	 * @param ColumnNum  列
	 * @param sheet   Excel worksheet
	 * @return Cell 单元格
	 */
	private Cell getTargetCellValue(int rowNum,int ColumnNum, Sheet sheet){
		Row row = sheet.getRow(rowNum);
		return row.getCell(ColumnNum);
	}
}

